package cn.wolfcode.crm.realms;


import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    public String getName() {
        return "myRealm";
    }

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 认证登录
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        Object principal = authenticationToken.getPrincipal();
        Employee employee = employeeService.getByUsername((String) principal);
        if (employee != null) {
            //在返回的时候凭证上加盐
            return new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(employee.getUsername()),getName());
        }
        return null;
    }


    /**
     * 认证权限
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("===========================================");
        Employee principal = (Employee) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //如果当前用户是超级管理员,则拥有全部的权限
        if (principal.getAdmin()) {
            info.addRole("ADMIN");
            info.addStringPermission("*:*");
        } else {
            info.addRoles(roleService.getRoleByEmployeeId(principal.getId()));
            info.addStringPermissions(permissionService.getPermissionByEmployeeId(principal.getId()));
        }
        return info;
    }
}
